--
-- Author: yawei.zhu
-- Date: 2018-09-17 16:44:47
--
-- DynastyTopView
--

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.DynastyTopScene

function ClassRef:init()
end

function ClassRef:updateGuildIcon(data, iconU, iconB)
	if data.flagBaseIcon then
        local baseIconPath = GD:getImagePath( Res.guildIconPath, data.flagBaseIcon )
        iconU:loadTexture( baseIconPath )
    end

    if data.flagAdditionalIcon then
        local additionalIconPath = GD:getImagePath( Res.guildIconPath, data.flagAdditionalIcon )
        iconB:loadTexture( additionalIconPath )
    end

    if data.flagBaseIconColor then
        iconU:setColor( app:getInst("NewguildModel"):getBaseIconColorList()[ data.flagBaseIconColor ] )
    end

    if data.flagAdditionalIconColor then
        iconB:setColor( app:getInst("NewguildModel"):getAdditionalIconColorList()[ data.flagAdditionalIconColor ] )
    end
end

function ClassRef:_tick(dt)
	if not self._tickCount then self._tickCount = 0 end
	self._tickCount = self._tickCount + 1
	if self._tickCount >= 6 then -- 公会战场景中，每6s拉取一次信息
		self._tickCount = 0
		executeFunc(self._onOperate, "reqDynastyTownInfo", self._townInfo.id)
	end

	-- 剩余时间
	local remainedTime = math.floor(self._townInfo.fightEndTime - app.session:getServerTime())
	if remainedTime < 0 then remainedTime = 0 end
	if remainedTime <= 30 then
		if not self._showCountDown then
			self._showCountDown = true
			executeFunc(self._onOperate, "showCountDonw", remainedTime)
		end
	end
	local str = string.format( L("dynastybattle_notice4"), TimeUtil.secondsToTime(remainedTime) )
	self._ui.time:setString(str)
end

function ClassRef:updateView(townInfo, myGuildID)
	self._townInfo = townInfo
	-- 我在左方，敌在右方
	local leftInfo = townInfo.defer
	local rightInfo = townInfo.atker
	local leftScore = townInfo.totalScoreDef
	local rightScore = townInfo.totalScoreAtk

	if myGuildID ~= leftInfo.guildId then
		leftInfo = townInfo.atker
		rightInfo = townInfo.defer
		leftScore = townInfo.totalScoreAtk
		rightScore = townInfo.totalScoreDef
	end

	self._ui.name_1:setString(leftInfo.guildName)
	self._ui.name_2:setString(rightInfo.guildName)

	self._ui.num_1:setString(leftScore)
	self._ui.num_2:setString(rightScore)

	self:updateGuildIcon(leftInfo, self._ui["icon_1/icon_u"], self._ui["icon_1/icon_b"])
	self:updateGuildIcon(rightInfo, self._ui["icon_2/icon_u"], self._ui["icon_2/icon_b"])

	-- 添加定时器
	if not self._cronsIdx then
		self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
		self:_tick()
	end
end

function ClassRef:removeScheduler()
	if self._cronsIdx then
		scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
	end
end

function ClassRef:onExit()
	self:removeScheduler()
end

return ClassRef
